package com.zl.tby.service.impl;

import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyCommandCenterQuery;
import com.zl.tby.model.TbyCommandCenter;
import com.zl.tby.repository.TbyCommandCenterRepo;
import com.zl.tby.service.ITbyCommandCenterService;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.IPage;
import org.noear.wood.annotation.Db;
import org.noear.wood.utils.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 指挥中心
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Component
public class TbyCommandCenterServiceImpl implements ITbyCommandCenterService {

    @Db
    private TbyCommandCenterRepo tbyCommandCenterRepo;

    @Override
    @Tran
    public R<TbyCommandCenter> add(TbyCommandCenter form) {
        form.setCreateBy(ToolsUtil.getLoginUserId());
        form.setCreateTime(LocalDateTime.now());
        long id = tbyCommandCenterRepo.insert(form, true);
        form.setId(id);
        return R.ok(form);
    }

    @Override
    @Tran
    public R<TbyCommandCenter> update(TbyCommandCenter form) {
        TbyCommandCenter entity = this.get(form.getId());
        if (entity == null) {
            return R.failed("数据不存在");
        }
        entity.setLatitude(form.getLatitude());
        entity.setLongitude(form.getLongitude());
        entity.setName(form.getName());
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        tbyCommandCenterRepo.updateById(entity, false);
        return R.ok(entity);
    }

    @Override
    public R<Void> delete(Long id) {
        // TODO 验证是否被引用
        int flag = tbyCommandCenterRepo.deleteById(id);
        return flag > 0 ? R.ok() : R.failed("删除失败");
    }

    @Override
    public TbyCommandCenter get(Long id) {
        return tbyCommandCenterRepo.selectById(id);
    }

    @Override
    public TbyPageResult<TbyCommandCenter> page(TbyCommandCenterQuery query) {
        IPage<TbyCommandCenter> iPage = tbyCommandCenterRepo.selectPage(query.getOffset(), query.getSize(), mp -> {
            mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getName()), "name like ?", "%" + query.getName() + "%");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        return new TbyPageResult(iPage, query);
    }

    @Override
    public List<TbyCommandCenter> list(TbyCommandCenterQuery query) {
        return tbyCommandCenterRepo.selectList(mapperWhereQ -> {
            mapperWhereQ.whereTrue().andIf(StringUtils.isNotEmpty(query.getName()), "name like ?", "%" + query.getName() + "%");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mapperWhereQ.orderBy(query.getOrder());
            }
        });
    }
}
